package com.scrx.ymg.service.orderform;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.scrx.ymg.dao.agent.IAgentInfoDao;
import com.scrx.ymg.dao.direct.IDirectDao;
import com.scrx.ymg.dao.distribution.IDistributionDao;
import com.scrx.ymg.dao.head.IHeadDao;
import com.scrx.ymg.dao.orderform.IOrderFormDao;
import com.scrx.ymg.dao.product.IProductDao;
import com.scrx.ymg.dao.seckill.ISeckillDao;
import com.scrx.ymg.dao.supermarket.ISuperMarketDao;
import com.scrx.ymg.dao.user.IUserDao;
import com.scrx.ymg.dao.util.IUtilDao;
import com.scrx.ymg.entity.Address;
import com.scrx.ymg.entity.AgentMoney;
import com.scrx.ymg.entity.Commission;
import com.scrx.ymg.entity.DirectInfo;
import com.scrx.ymg.entity.DirectMoney;
import com.scrx.ymg.entity.DirectProduct;
import com.scrx.ymg.entity.Distribution;
import com.scrx.ymg.entity.DividedInto;
import com.scrx.ymg.entity.HeadMoney;
import com.scrx.ymg.entity.OrderForm;
import com.scrx.ymg.entity.OrderFormDetails;
import com.scrx.ymg.entity.OrderReturn;
import com.scrx.ymg.entity.OtherInfo;
import com.scrx.ymg.entity.OtherMoney;
import com.scrx.ymg.entity.ProductEvaluate;
import com.scrx.ymg.entity.SeckillProduct;
import com.scrx.ymg.entity.SuperMarketEntrepot;
import com.scrx.ymg.entity.SuperMarketInfo;
import com.scrx.ymg.entity.SupermarketMoney;
import com.scrx.ymg.entity.User;
import com.scrx.ymg.entity.UserComplain;
import com.scrx.ymg.service.address.IAddressService;
import com.scrx.ymg.util.LatLonUtil;
import com.scrx.ymg.util.WeixinUtil;

@Service("orderFormService")
public class OrderFormServiceImpl implements IOrderFormService {

	@Autowired
	private IOrderFormDao orderFormDao;
	@Autowired
	private ISuperMarketDao superMarketDao;
	@Autowired
	private IHeadDao headao;
	@Autowired
	private IUserDao userDao;
	@Autowired
	private IProductDao productDao;
	@Autowired
	private IAddressService adds;
	@Autowired
	private IDirectDao directDao;
	@Autowired
	private ISeckillDao seckilldao;
	@Autowired
	private IAgentInfoDao agentdao;

	@Autowired
	private IUtilDao utildao;

	@Autowired
	private IDistributionDao disdao;

	public String createOrderForm(User user, SuperMarketInfo superinfo, Address add, double shippingFee,
			double totalMoney, int paymentType, List<OrderFormDetails> details, int status) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String orderid = orderIDGenerativeRule("c", user.getId(), superinfo.getId());
		OrderForm order = new OrderForm();
		order.setAddress(add.getLocationAdd() + add.getExpressageAdd());// 订单送货地址
		order.setOrderFormId(orderid);// 订单编号
		order.setOrderFormTime(formatter.format(new Date()));// 订单时间
		order.setPaymentType(paymentType);// 支付类型
		order.setPhone(add.getPhone());// 电话
		order.setTypeId(1);
		order.setShippingFee(shippingFee);// 配送费
		order.setStatus(status);// 订单状态 1.待发货 2.待收货,3.待评价,4.退货,0.已取消订单
		order.setSuperId(superinfo.getId());// 所属超市
		order.setInactive1(1);// 订单类型1.超市,2,秒杀团购,3直营
		order.setInactive2(superinfo.getName());// 所属超市名称
		order.setTotalMoney(totalMoney);// 总价
		order.setUserId(user.getId());// 订单消费者
		order.setUserName(add.getConsignee());// 收货人
		// 修改超市仓库商品数量及销量
		List<SuperMarketEntrepot> superEns = orderFormDao.getSuperMarketEntrepotes(details);
		for (int i = 0; i < details.size(); i++) {
			if (superEns.get(i).getHot() == 0) {// 超市商品
				if (superEns.get(i).getRepertory() >= details.get(i).getQuantity()) {
					superEns.get(i).setRepertory(superEns.get(i).getRepertory() - details.get(i).getQuantity());
					superEns.get(i).setSales(superEns.get(i).getSales() + details.get(i).getQuantity());
					if (superEns.get(i).getRepertory() <= 0) {
						superEns.get(i).setPutaway(0);
					}
				} else {
					return "251";
				}
			} else if (superEns.get(i).getHot() == 1) {// 爆款商品
				if (superEns.get(i).getInactive3() >= details.get(i).getQuantity()) {
					superEns.get(i).setSales(superEns.get(i).getSales() + details.get(i).getQuantity());
					superEns.get(i).setInactive3(superEns.get(i).getInactive3() - details.get(i).getQuantity());
					if (superEns.get(i).getInactive3() <= 0) {
						superEns.get(i).setPutaway(0);
					}
				} else {
					return "251";
				}
			}

			details.get(i).setProductImg(superEns.get(i).getProductSimg());
		}
		// 1.2生成超市会员
		if (user.getBelongSupermarket() == null) {
			user.setBelongSupermarket(superinfo.getId());
			user.setConsumeMoney(user.getConsumeMoney() + order.getTotalMoney());
			user.setOrderNum(user.getOrderNum() + 1);
			user.setAgentId(superinfo.getAgentId());
		}
		return orderFormDao.saveOrderFormAndDetails(user, order, details, superEns);
	}

	public String createOrderFormWX(User user, SuperMarketInfo superinfo, Address add, double shippingFee,
			double totalMoney, int paymentType, List<OrderFormDetails> details, int status) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String orderid = orderIDGenerativeRule("c", user.getId(), superinfo.getId());
		OrderForm order = new OrderForm();
		order.setAddress(add.getLocationAdd() + add.getExpressageAdd());// 订单送货地址
		order.setOrderFormId(orderid);// 订单编号
		order.setOrderFormTime(formatter.format(new Date()));// 订单时间
		order.setPaymentType(paymentType);// 支付类型
		order.setPhone(add.getPhone());// 电话
		order.setTypeId(1);
		order.setShippingFee(shippingFee);// 配送费
		order.setStatus(status);// 订单状态 1.待发货 2.待收货,3.待评价,4.退货,0.已取消订单
		order.setSuperId(superinfo.getId());// 所属超市
		order.setInactive1(1);// 订单类型1.超市,2,秒杀团购,3直营
		order.setInactive2(superinfo.getName());// 所属超市名称
		order.setTotalMoney(totalMoney);// 总价
		order.setUserId(user.getId());// 订单消费者
		order.setUserName(add.getConsignee());// 收货人
		// 修改超市仓库商品数量及销量
		List<SuperMarketEntrepot> superEns = orderFormDao.getSuperMarketEntrepotes(details);
		for (int i = 0; i < details.size(); i++) {
			if (superEns.get(i).getHot() == 0) {// 超市商品
				if (superEns.get(i).getRepertory() >= details.get(i).getQuantity()) {
					superEns.get(i).setRepertory(superEns.get(i).getRepertory() - details.get(i).getQuantity());
					if (superEns.get(i).getRepertory() <= 0) {
						superEns.get(i).setPutaway(0);
					}
				} else {
					return "251";
				}
			} else if (superEns.get(i).getHot() == 1) {// 爆款商品
				if (superEns.get(i).getInactive3() >= details.get(i).getQuantity()) {
					superEns.get(i).setInactive3(superEns.get(i).getInactive3() - details.get(i).getQuantity());
					if (superEns.get(i).getInactive3() <= 0) {
						superEns.get(i).setPutaway(0);
					}
				} else {
					return "251";
				}
			}
			details.get(i).setProductImg(superEns.get(i).getProductSimg());
		}
		// 1.2生成超市会员
		if (user.getBelongSupermarket() == null) {
			user.setBelongSupermarket(superinfo.getId());
			user.setConsumeMoney(user.getConsumeMoney() + order.getTotalMoney());
			user.setOrderNum(user.getOrderNum() + 1);
			user.setAgentId(superinfo.getAgentId());
		}
		String msg = orderFormDao.saveOrderFormAndDetails(user, order, details, superEns);
		if (msg.equals("true")) {
			msg = orderid;
		}
		return msg;
	}

	/**
	 * 订单编号生成规则
	 * 
	 * @param userID
	 * @param superID
	 * @return
	 */
	public String orderIDGenerativeRule(String flag, int userID, int superID) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyMMddHHmmss");
		String date = formatter.format(new Date());
		String orderid = flag + superID + date + userID;
		return orderid;
	}

	public List<OrderForm> getOrderFormGroupStatus(String userID) {

		return orderFormDao.getOrderFormGroupStatus(userID);
	}

	public List getOrderFormByStatus(String userid, String status) {
		return orderFormDao.getOrderFormByStatus(userid, status);
	}

	public List getOrderFormByUserID(String userid) {
		return orderFormDao.getOrderFormByUserID(userid);
	}

	public String takeDeliveryOfGoods(String userID, int ID) {
		// 1.改变订单状态
		OrderForm order = orderFormDao.getOrderFormByID(ID);
		order.setStatus(3);// 收货后状态改变为3:已完成
		if (order.getTypeId() == 1) {
			SupermarketMoney money = superMarketDao.findSupermarketMoneyByID(order.getSuperId());
			money.setSuperMoney(money.getSuperMoney() + order.getTotalMoney());
			money.setTotalMoney(money.getTotalMoney() + order.getTotalMoney());
			if (order.getPaymentType() == 1) {// 2.超市货到付款金额增加
				money.setLocalMoney(money.getLocalMoney() + order.getTotalMoney());

			} else if (order.getPaymentType() == 2) {
				money.setOnlineMoney(money.getOnlineMoney() + order.getTotalMoney());
				money.setAccountMoney(money.getAccountMoney() + order.getTotalMoney());
			}
			User user = userDao.findById(Integer.parseInt(userID));
			user.setOrderNum(user.getOrderNum() + 1);
			user.setConsumeMoney(user.getConsumeMoney() + order.getTotalMoney());
			return orderFormDao.takeDeliveryOfGoods(order, money, user);
		} else if (order.getTypeId() == 3) {
			return directTakeDelivery(order);
			// return directTakeDeliveryYongJin(order);
		}
		return "false";
	}

	/*
	 * public String takeDeliveryOfGoods(String userID, int ID) { // 1.改变订单状态
	 * OrderForm order = orderFormDao.getOrderFormByID(ID);
	 * order.setStatus(3);// 收货后状态改变为3:已完成 if(order.getTypeId()==1){
	 * SupermarketMoney money =
	 * superMarketDao.findSupermarketMoneyByID(order.getSuperId());
	 * money.setSuperMoney(money.getSuperMoney() + order.getTotalMoney());
	 * money.setTotalMoney(money.getTotalMoney() + order.getTotalMoney()); if
	 * (order.getPaymentType() == 1) {// 2.超市货到付款金额增加
	 * money.setLocalMoney(money.getLocalMoney() + order.getTotalMoney());
	 * 
	 * } else if (order.getPaymentType() == 2) {
	 * money.setOnlineMoney(money.getOnlineMoney() + order.getTotalMoney());
	 * money.setAccountMoney(money.getAccountMoney() + order.getTotalMoney()); }
	 * User user = userDao.findById(Integer.parseInt(userID));
	 * user.setOrderNum(user.getOrderNum() + 1);
	 * user.setConsumeMoney(user.getConsumeMoney() + order.getTotalMoney());
	 * return orderFormDao.takeDeliveryOfGoods(order, money, user); }else
	 * if(order.getTypeId()==3){ return directTakeDelivery(order); } return
	 * "false"; }
	 */
	public String directTakeDeliveryYongJin(int ID) {
		// 1.改变订单状态
		OrderForm oldorder = orderFormDao.getOrderFormByID(ID);

		List<OrderFormDetails> details = orderFormDao.getOrderFormDetailsByOrderFormID(oldorder.getOrderFormId());
		oldorder.setStatus(3);// 收货后状态改变为3:已完成
		Commission ssion = utildao.getCommission();
		double orderMoney = oldorder.getTotalMoney();// 订单金额
		double OneLevel = 0;
		User user = userDao.findById(oldorder.getUserId());
		// 一级分销
		Distribution distribution = null;
		Distribution distribution2 = null;
		// 获得当前商品分销金额百分比
		double sumMoney = 0.0;
		for (int i = 0; i < details.size(); i++) {
			DirectProduct product = directDao.getDirectProductById(details.get(i).getProductId());
			// 商品价格
			double pPrice = product.getHotPrice();
			// 商品比例分销
			double bili = product.getProfit() / 100.0;
			// 单个商品分销金额
			double danMoney = pPrice * bili * details.get(i).getQuantity();
			sumMoney += danMoney;
		}
		double oneMoney = (ssion.getOneLevel() / 100.0) * sumMoney;
		double twoMoney = (ssion.getTwoLevel() / 100.0) * sumMoney;
		DirectMoney directMoney = null;
		// 如果有一级分销并且订单金额在可分佣金范围
		if (user.getReferrerId() != -1 && orderMoney >= ssion.getBrokerageMin()
				&& orderMoney <= ssion.getBrokerageMax()) {
			User user2 = userDao.findById(user.getReferrerId());
			// 如果有二级分销
			if (user2.getReferrerId() != -1) {
				// 一级分销金额增加
				distribution = disdao.getDistribution(user.getReferrerId());
				distribution.setFxBrokerage(distribution.getFxBrokerage() + oneMoney);
				distribution.setKtxBrokerage(distribution.getKtxBrokerage() + oneMoney);
				// 二级分销金额增加
				distribution2 = disdao.getDistribution(user2.getReferrerId());
				distribution2.setFxBrokerage(distribution2.getFxBrokerage() + twoMoney);
				distribution2.setKtxBrokerage(distribution2.getKtxBrokerage() + twoMoney);
			} else {
				// 没有二级分销
				// 一级分销金额增加
				distribution = disdao.getDistribution(user.getReferrerId());
				distribution.setFxBrokerage(distribution.getFxBrokerage() + twoMoney + oneMoney);
				distribution.setKtxBrokerage(distribution.getKtxBrokerage() + twoMoney + oneMoney);
			}
			// 没有分销佣金。商家只获得金额
			directMoney = directDao.getDirectMoney(1);
			directMoney.setAccountMoney(directMoney.getAccountMoney() + orderMoney - sumMoney);
			directMoney.setTotalMoney(directMoney.getTotalMoney() + orderMoney - sumMoney);

		} else {
			// 没有上级佣金全部给商户
			directMoney = directDao.getDirectMoney(1);
			directMoney.setAccountMoney(directMoney.getAccountMoney() + orderMoney);
			directMoney.setTotalMoney(directMoney.getTotalMoney() + orderMoney);
		}
		return disdao.updateDistributionAndOrder(distribution, distribution2, oldorder, directMoney);

	}

	public String directTakeDelivery(OrderForm oldorder) {
		DividedInto into = headao.selectDividedInto();// 1.得到分成设置
		User user = userDao.findById(oldorder.getUserId());
		double agent_fc = into.getAgentZyDivided() / 100;// 代理商分成比例
		double super_fc = into.getSuperZyDivided() / 100;// 超市分成比例
		double head_fc = into.getHeadZyDivided() / 100;// 总部分成比例

		double directgetMoney = 0;// 直营商家可得金额
		double qt_getMoney = 0;// 超市,总部,代理商家可得金额

		if (oldorder != null && oldorder.getTypeId() == 3) {// 直营订单
			List<OrderFormDetails> details = orderFormDao.getOrderFormDetailsByOrderFormID(oldorder.getOrderFormId());
			HeadMoney headMoney = headao.getHeadMoney();
			DirectProduct product = directDao.getDirectProductById(details.get(0).getDirectId());
			oldorder.setStatus(3);
			/* 直营商家营业额入账 */
			DirectInfo direct = directDao.getDirectInfoById(oldorder.getSuperId());// 异业商家id
			double percentage = (100 - Double.parseDouble(product.getProfit().toString())) / 100;// 直营商家可得分配比率
			double qt_percentage = Double.parseDouble(product.getProfit().toString()) / 100;// 其他商家可得分配比率
			qt_getMoney = oldorder.getTotalMoney() * qt_percentage;
			directgetMoney = oldorder.getTotalMoney() * percentage;
			DirectMoney directMoney = directDao.getDirectMoney(direct.getId());
			directMoney.setAccountMoney(directMoney.getAccountMoney() + directgetMoney);
			directMoney.setTotalMoney(directMoney.getTotalMoney() + directgetMoney);
			/* 根据金额给各商家分成 */
			// 1.该会员不属于超市代理商则分给总部
			if (user.getBelongSupermarket() == null) {
				double superMoney_fc = qt_getMoney * super_fc;// 超市可分得利润
				double agentMoney_fc = qt_getMoney * agent_fc;// 代理商可分得利润
				double headMoney_fc = qt_getMoney * head_fc;// 总部克分得利润
				headMoney.setHeadDirectMoney(
						headMoney.getHeadDirectMoney() + superMoney_fc + agentMoney_fc + headMoney_fc);
				headMoney.setHeadAccountMoney(
						headMoney.getHeadAccountMoney() + superMoney_fc + agentMoney_fc + headMoney_fc);
				headMoney.setHeadTotalMoney(
						headMoney.getHeadTotalMoney() + superMoney_fc + agentMoney_fc + headMoney_fc);
				return orderFormDao.updateObjects(oldorder, directMoney, null, null, headMoney);
			} else {
				// 1.超市
				SupermarketMoney superMoney = superMarketDao.getSupermarketMoneyInfo(user.getBelongSupermarket());
				double superMoney_fc = qt_getMoney * super_fc;// 超市可分得利润
				superMoney.setDirectMoney(superMoney.getDirectMoney() + superMoney_fc);// 超市团购提成记录
				superMoney.setAccountMoney(superMoney.getAccountMoney() + superMoney_fc);// 超市可提现金额
				superMoney.setTotalMoney(superMoney.getTotalMoney() + superMoney_fc);
				// 2.代理商
				SuperMarketInfo info = superMarketDao.findByID(user.getBelongSupermarket());
				AgentMoney agentMoney = agentdao.getAgentMoneyInfo(info.getAgentId());
				double agentMoney_fc = qt_getMoney * agent_fc;// 超市可分得利润
				agentMoney.setDirectMoney(agentMoney.getDirectMoney() + agentMoney_fc);
				agentMoney.setAccountMoney(agentMoney.getAccountMoney() + agentMoney_fc);
				agentMoney.setTotalMoney(agentMoney.getTotalMoney() + agentMoney_fc);
				// 3.总部
				double headMoney_fc = qt_getMoney * head_fc;
				headMoney.setHeadDirectMoney(headMoney.getHeadDirectMoney() + headMoney_fc);
				headMoney.setHeadAccountMoney(headMoney.getHeadAccountMoney() + headMoney_fc);
				headMoney.setHeadTotalMoney(headMoney.getHeadTotalMoney() + headMoney_fc);

				return orderFormDao.updateObjects(oldorder, directMoney, superMoney, agentMoney, headMoney);
			}
			/* 根据金额给各商家分成 */

		}

		return "false";
	}

	public String TheSupermarketDelivery(String orderFormID, String trackingNum) {
		// 1.拿到订单
		OrderForm orderForm = orderFormDao.getOrderFormByOrderFormID(orderFormID);
		if (orderForm.getStatus() == 1) {
			if (orderForm.getTypeId() == 3) {// 直营专区
				orderForm.setTrackingNum(trackingNum);
			}
			// 2.修改状态
			orderForm.setStatus(2);// 修改为2:待收货
			// 3.保存
			orderFormDao.update(orderForm);
			return "true";
		} else {
			return "false";
		}
	}

	public List<OrderForm> getOrderFormBySuperID(String userID, String status) {

		return (List<OrderForm>) orderFormDao.getOrderFormBySuperID(userID, status);
	}

	public Map<Object, Object> getOrderFormBySuper(OrderForm orderform, String startTime, String endTime, int pageNum,
			int pageCount) {
		return orderFormDao.getOrderFormBySuper(orderform, startTime, endTime, pageNum, pageCount);
	}

	public Map<Object, Object> getOrderFormBySuper(OrderForm orderform, int pageNum, int pageCount) {
		return orderFormDao.getOrderFormBySuper(orderform, pageNum, pageCount);
	}

	public String cancelOrderForm(OrderForm order) {
		order = orderFormDao.getOrderFormByID(order.getId());

		if (order.getStatus() == 1) {// 判断状态是待发货才能取消订单
			order.setStatus(0);// 取消订单
			List<SuperMarketEntrepot> entrlist = new ArrayList<SuperMarketEntrepot>();
			List<OrderFormDetails> list = orderFormDao.getOrderFormDetailsByOrderFormID(order.getOrderFormId());
			for (OrderFormDetails details : list) {
				SuperMarketEntrepot entr = productDao.selectByID(details.getProductId());
				if (entr.getHot() == 1) {// 爆款
					entr.setInactive3(entr.getInactive3() + details.getQuantity());
				} else if (entr.getHot() == 0) {// 超市
					entr.setRepertory(entr.getRepertory() + details.getQuantity());
				}
				entrlist.add(entr);
			}

			return orderFormDao.update(order, entrlist);
		} else if (order.getStatus() == 7 || order.getStatus() == 3 || order.getStatus() == 6) {
			order.setStatus(8);// 操作完毕订单
			return orderFormDao.update(order);
		} else {
			return "已删除";
		}

	}

	public String returnsOrderForm(OrderForm order) {
		OrderForm oldorder = orderFormDao.getOrderFormByID(order.getId());
		if (oldorder.getStatus() == 2) {
			oldorder.setStatus(5);
			oldorder.setRemark(order.getRemark());
			oldorder.setReturnCause(order.getReturnCause());
			// 创建退货订单
			return orderFormDao.update(oldorder);
		} else {
			return "已退货";
		}

	}

	public String evaluateOrderForm(int orderId, int userId, ProductEvaluate peva) {
		OrderForm order = orderFormDao.getOrderFormByID(orderId);
		List<OrderFormDetails> details = orderFormDao.getOrderFormDetailsByOrderFormID(order.getOrderFormId());
		User user = userDao.findById(userId);
		List<ProductEvaluate> pevalist = new ArrayList<ProductEvaluate>();
		// 2.修改订单状态
		if (order.getStatus() == 3) {
			order.setStatus(4);
			LatLonUtil util = new LatLonUtil();
			for (OrderFormDetails detail : details) {
				ProductEvaluate temp = new ProductEvaluate();
				temp.setEvaluateContent(peva.getEvaluateContent());
				temp.setEvaluateLevel(peva.getEvaluateLevel());
				temp.setEvaluateTime(util.newdate());
				if (order.getTypeId() == 0 || order.getTypeId() == 2) {
					temp.setProductId(detail.getSeckillId());// 评价订单 商品id
																// 要根据商品类型来选择用哪个字段
				} else if (order.getTypeId() == 1) {// 超市订单
					temp.setProductId(detail.getProductId());
				} else if (order.getTypeId() == 3) {// 直营订单
					temp.setProductId(detail.getDirectId());
				}

				temp.setTypeId(order.getTypeId());
				temp.setUserName(user.getUserName());
				pevalist.add(temp);
			}
			// 3.事务提交
			return orderFormDao.evaluateOrderForm(order, pevalist);

		} else {
			return "false";
		}

	}

	public String complaintOrderForm(OrderForm order, UserComplain com) {
		order = orderFormDao.getOrderFormByID(order.getId());

		// 2.修改订单状态
		if (order.getStatus() == 5 || order.getStatus() == 6) {
			order.setStatus(7);
			com.setSuperId(order.getSuperId());
			LatLonUtil util = new LatLonUtil();
			com.setComplainTime(util.newdate());
			// 3.事务提交
			return orderFormDao.complaintOrderForm(order, com);
		} else {
			return "已投诉";
		}

		// 3.事务提交

	}

	public String reminder(int superID) {
		return orderFormDao.getSendPhone(superID);
	}

	public Map<Object, Object> getUserReturn(OrderReturn order, int pageCount, int pageNum) {
		return orderFormDao.getUserReturn(order, pageCount, pageNum);
	}

	public String disposeReturn(String orderFormID) {
		OrderForm order = orderFormDao.getOrderFormByOrderFormID(orderFormID);
		String msg = "false";
		if (order != null && order.getStatus() == 5 && order.getTypeId() == 1 && order.getPaymentType() == 1) {
			// SupermarketMoney money =
			// superMarketDao.getSupermarketMoneyInfo(order.getSuperId());
			// money.setSuperMoney(money.getSuperMoney()-order.getTotalMoney());
			// money.setTotalMoney(money.getTotalMoney()-order.getTotalMoney());
			// money.setLocalMoney(money.getLocalMoney()-order.getTotalMoney());
			order.setStatus(6); // 1.改变订单状态
			List<SuperMarketEntrepot> entrlist = new ArrayList<SuperMarketEntrepot>();
			List<OrderFormDetails> list = orderFormDao.getOrderFormDetailsByOrderFormID(order.getOrderFormId());
			for (OrderFormDetails details : list) {
				SuperMarketEntrepot entr = productDao.selectByID(details.getProductId());
				if (entr.getHot() == 1) {// 爆款
					entr.setInactive3(entr.getInactive3() + details.getQuantity());
				} else if (entr.getHot() == 0) {// 超市
					entr.setRepertory(entr.getRepertory() + details.getQuantity());
				}
				entrlist.add(entr);
			}
			msg = orderFormDao.setOrderFormAndOrderReturn(order, null, entrlist);
		}
		return msg;
	}

	public String returnTransferPay(String orderFormID) {
		OrderForm order = orderFormDao.getOrderFormByOrderFormID(orderFormID);
		HeadMoney headMoney = headao.getHeadMoney();
		String msg = "false";
		if (order != null && order.getStatus() == 5 && order.getTypeId() == 1) {
			order.setStatus(6); // 1.改变订单状态
			List<SuperMarketEntrepot> entrlist = new ArrayList<SuperMarketEntrepot>();
			List<OrderFormDetails> list = orderFormDao.getOrderFormDetailsByOrderFormID(order.getOrderFormId());
			for (OrderFormDetails details : list) {
				SuperMarketEntrepot entr = productDao.selectByID(details.getProductId());
				if (entr.getHot() == 1) {// 爆款
					entr.setInactive3(entr.getInactive3() + details.getQuantity());
				} else if (entr.getHot() == 0) {// 超市
					entr.setRepertory(entr.getRepertory() + details.getQuantity());
				}
				entrlist.add(entr);
			}
			if (order.getPaymentType() == 2) {
				headMoney.setTerraceAccountMoney(headMoney.getTerraceAccountMoney() - order.getTotalMoney());// 平台可提现金额
				headMoney.setTerraceTotalMoney(headMoney.getTerraceTotalMoney() - order.getTotalMoney());// 平台营业总金额
				headMoney.setTerraceSuperMoney(headMoney.getTerraceSuperMoney() - order.getTotalMoney());// 平台超市在线总营业金额
			}
			msg = orderFormDao.setOrderFormAndOrderReturn(order, headMoney, entrlist);
		} else if (order != null && order.getStatus() == 5 && order.getTypeId() == 3) {
			order.setStatus(6); // 1.改变订单状态
			headMoney.setTerraceAccountMoney(headMoney.getTerraceAccountMoney() - order.getTotalMoney());// 平台可提现金额
			headMoney.setTerraceTotalMoney(headMoney.getTerraceTotalMoney() - order.getTotalMoney());// 平台营业总金额
			headMoney.setTerraceDirectMoney(headMoney.getTerraceDirectMoney() - order.getTotalMoney());// 平台超市在线总营业金额
			msg = orderFormDao.setOrderFormAndOrderReturn(order, headMoney, null);
		}
		return msg;
	}

	public List<OrderFormDetails> getOrderFormDetailsByOrderFormID(String orderFormId) {

		return orderFormDao.getOrderFormDetailsByOrderFormID(orderFormId);
	}

	public OrderForm getOrderFormByOrderId(String orderId) {
		return orderFormDao.getOrderFormByOrderFormID(orderId);
	}

	public String updateOrderForm(OrderForm order) {

		return orderFormDao.update(order);
	}

	public String updateOrderFormAndHeadMoney(OrderForm order) {
		HeadMoney headMoney = headao.getHeadMoney();
		if (order.getTypeId() == 1) {// 超市订单
			headMoney.setTerraceSuperMoney(headMoney.getTerraceSuperMoney() + order.getTotalMoney());// 平台超市在线总营业金额
		} else if (order.getTypeId() == 2) {// 团购订单
			List<OrderFormDetails> list = orderFormDao.getOrderFormDetailsByOrderFormID(order.getOrderFormId());
			SeckillProduct product = seckilldao.getSeckillOne(list.get(0).getSeckillId());
			product.setSales(product.getSales() + list.get(0).getQuantity());
			headMoney.setTerraceGroupMoney(headMoney.getTerraceGroupMoney() + order.getTotalMoney());// 平台团购金额
			headMoney.setTerraceAccountMoney(headMoney.getTerraceAccountMoney() + order.getTotalMoney());// 平台可提现金额
			headMoney.setTerraceTotalMoney(headMoney.getTerraceTotalMoney() + order.getTotalMoney());// 平台营业总金额
			return orderFormDao.updateOrderFormAndHeadMoney(order, headMoney, product);
		} else if (order.getTypeId() == 3) {// 直营订单
			headMoney.setTerraceDirectMoney(headMoney.getTerraceDirectMoney() + order.getTotalMoney());// 平台团购金额
		}
		headMoney.setTerraceAccountMoney(headMoney.getTerraceAccountMoney() + order.getTotalMoney());// 平台可提现金额
		headMoney.setTerraceTotalMoney(headMoney.getTerraceTotalMoney() + order.getTotalMoney());// 平台营业总金额
		return orderFormDao.updateOrderFormAndHeadMoney(order, headMoney);
	}

	public String updateDirectOrderFormAndHeadMoney(OrderForm order) {
		HeadMoney headMoney = headao.getHeadMoney();
		List<OrderForm> list = orderFormDao.getOrderFormListByPreant(order.getId());
		for (int i = 0; i < list.size(); i++) {
			list.get(i).setStatus(1);
		}
		headMoney.setTerraceDirectMoney(headMoney.getTerraceDirectMoney() + order.getTotalMoney());// 平台直营金额
		headMoney.setTerraceAccountMoney(headMoney.getTerraceAccountMoney() + order.getTotalMoney());// 平台可提现金额
		headMoney.setTerraceTotalMoney(headMoney.getTerraceTotalMoney() + order.getTotalMoney());// 平台营业总金额
		return orderFormDao.updateOrderFormAndHeadMoney(order, headMoney, list);
	}

	public String returnOrderForm(OrderForm order) {
		HeadMoney headMoney = headao.getHeadMoney();
		if (order.getTypeId() == 1) {// 超市订单
			if (order.getStatus() == 1) {// 待发货
				order.setStatus(0);// 取消订单
				headMoney.setTerraceAccountMoney(headMoney.getTerraceAccountMoney() - order.getTotalMoney());// 平台可提现金额
				headMoney.setTerraceTotalMoney(headMoney.getTerraceTotalMoney() - order.getTotalMoney());// 平台营业总金额
				headMoney.setTerraceSuperMoney(headMoney.getTerraceSuperMoney() - order.getTotalMoney());// 平台超市在线总营业金额
			}
		} else if (order.getTypeId() == 2) {// 团购订单
			if (order.getStatus() == 2) {// 待收货
				order.setStatus(0);// 取消订单
				headMoney.setTerraceAccountMoney(headMoney.getTerraceAccountMoney() - order.getTotalMoney());// 平台可提现金额
				headMoney.setTerraceTotalMoney(headMoney.getTerraceTotalMoney() - order.getTotalMoney());// 平台营业总金额
				headMoney.setTerraceGroupMoney(headMoney.getTerraceGroupMoney() - order.getTotalMoney());// 平台团购营业金额
			}
		} else if (order.getTypeId() == 3) {
			if (order.getStatus() == 1) {// 待发货
				order.setStatus(0);// 取消订单
				headMoney.setTerraceAccountMoney(headMoney.getTerraceAccountMoney() - order.getTotalMoney());// 平台可提现金额
				headMoney.setTerraceTotalMoney(headMoney.getTerraceTotalMoney() - order.getTotalMoney());// 平台营业总金额
				headMoney.setTerraceDirectMoney(headMoney.getTerraceDirectMoney() - order.getTotalMoney());// 平台超市在线总营业金额
			}

		} else {
			return "false";
		}

		return orderFormDao.updateOrderFormAndHeadMoney(order, headMoney);
	}

	public String createDirectOrderFormNew(User user, String addressID, Double totalMoney,
			List<OrderFormDetails> details, int status) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		// 1.生成总订单用于微信支付

		String payorderId = orderIDGenerativeRule("pay", user.getId(), 1);
		Address add = adds.getAddressByID(addressID);
		List<DirectProduct> products = orderFormDao.getDirectProductByOrderFormDetails(details);

		OrderForm order = new OrderForm();
		order.setOrderFormId(payorderId);
		order.setStatus(status);// 微信下单状态 -1为支付后没有返回，返回支付成功后 其他方法修改为1订单状态 1.待发货
								// 2.待收货,3.待评价,4.退货,0.已取消订单
		order.setTotalMoney(totalMoney);
		order.setAddress(add.getLocationAdd() + add.getExpressageAdd());// 订单送货地址
		order.setOrderFormTime(formatter.format(new Date()));// 订单时间
		order.setPaymentType(2);// 支付类型
		order.setPhone(add.getPhone());// 电话
		order.setTypeId(3);
		order.setTotalMoney(totalMoney);// 总价
		order.setUserId(user.getId());// 订单消费者
		order.setUserName(add.getConsignee());// 收货人
		order.setInactive1(3);
		order.setSuperId(1);
		// 3.每个订单的详情为该商品
		List<OrderFormDetails> orderFormDetails = new ArrayList<OrderFormDetails>();
		// 2.根据为每一个商品生成一个订单详情
		for (int i = 0; i < details.size(); i++) {
			products.get(i).setSales(products.get(i).getSales() + details.get(i).getQuantity());// 修改直营商品销量
			OrderFormDetails detail = details.get(i);
			DirectInfo info = directDao.getDirectInfoById(detail.getShopsId());
			detail.setOrderFormId(payorderId);
			detail.setOrderDetailsId(order.getOrderFormId() + (i + 1));
			detail.setStatus(1);
			detail.setProductImg(products.get(i).getThumbnailImg());
			detail.setProductName(products.get(i).getProductName());
			detail.setProductId(products.get(i).getId());
			orderFormDetails.add(detail);
		}

		order.setOrderFormDetails(orderFormDetails);
		user.setOrderNum(user.getOrderNum() + details.size());
		user.setConsumeMoney(user.getConsumeMoney() + totalMoney);
		// String msg = orderFormDao.saveOrderFormListAndDetails(user, order,
		// orderlist, products);
		String msg = orderFormDao.insertPurchaseOrder(user, order, products);
		if (msg.equals("true")) {
			msg = payorderId;
		}
		return msg;
	}

	public String createDirectOrderForm(User user, String addressID, Double totalMoney, List<OrderFormDetails> details,
			int status) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		// 1.生成总订单用于微信支付
		OrderForm payorder = new OrderForm();
		String payorderId = orderIDGenerativeRule("pay", user.getId(), 1);
		payorder.setOrderFormId(payorderId);
		payorder.setStatus(status);// 微信下单状态 -1为支付后没有返回，返回支付成功后 其他方法修改为1
		payorder.setTotalMoney(totalMoney);
		Address add = adds.getAddressByID(addressID);
		List<OrderForm> orderlist = new ArrayList<OrderForm>();
		List<DirectProduct> products = orderFormDao.getDirectProductByOrderFormDetails(details);
		// 2.根据为每一个商品生成一个订单
		for (int i = 0; i < details.size(); i++) {
			products.get(i).setSales(products.get(i).getSales() + details.get(i).getQuantity());// 修改直营商品销量
			OrderFormDetails detail = details.get(i);
			DirectInfo info = directDao.getDirectInfoById(detail.getShopsId());
			OrderForm order = new OrderForm();
			String orderFormId = orderIDGenerativeRule("z" + i, user.getId(), info.getId());
			order.setAddress(add.getLocationAdd() + add.getExpressageAdd());// 订单送货地址
			order.setOrderFormId(orderFormId);// 订单编号
			order.setOrderFormTime(formatter.format(new Date()));// 订单时间
			order.setPaymentType(2);// 支付类型
			order.setPhone(add.getPhone());// 电话
			order.setTypeId(3);
			order.setStatus(status);// 订单状态 1.待发货 2.待收货,3.待评价,4.退货,0.已取消订单
			order.setSuperId(info.getId());// 所属超市
			order.setInactive2(info.getDirectName());// 所属超市名称
			order.setTotalMoney(totalMoney);// 总价
			order.setUserId(user.getId());// 订单消费者
			order.setUserName(add.getConsignee());// 收货人
			order.setInactive1(3);
			// 3.每个订单的详情为该商品
			List<OrderFormDetails> orderFormDetails = new ArrayList<OrderFormDetails>();
			detail.setOrderFormId(orderFormId);
			detail.setOrderDetailsId(order.getOrderFormId() + (i + 1));
			detail.setStatus(1);
			detail.setProductImg(products.get(i).getThumbnailImg());
			detail.setProductName(products.get(i).getProductName());
			detail.setProductId(products.get(i).getId());
			orderFormDetails.add(detail);
			order.setOrderFormDetails(orderFormDetails);
			orderlist.add(order);
		}
		user.setOrderNum(user.getOrderNum() + details.size());
		user.setConsumeMoney(user.getConsumeMoney() + totalMoney);
		String msg = orderFormDao.saveOrderFormListAndDetails(user, payorder, orderlist, products);
		if (msg.equals("true")) {
			msg = payorderId;
		}
		return msg;
	}

	public OrderForm getOrderFormById(int Id) {
		return orderFormDao.getOrderFormByID(Id);
	}

	public String updateOrderFormSendMessage(OrderForm order) {
		order.setStatus(1);

		String flag = orderFormDao.update(order);
		if (flag.equals("true")) {
			List<OrderFormDetails> details = orderFormDao.getOrderFormDetailsByOrderFormID(order.getOrderFormId());
			WeixinUtil.send_template_message(userDao.findById(order.getUserId()).getUserId(), order, details);
		}
		return flag;
	}

}
